import {Component, OnInit, AfterViewInit, ViewChildren, QueryList} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {BLOCK_URL, SERVER_URL} from '../../config';
import {HttpClient} from '@angular/common/http';
import {ReturnData} from '../../login/login.component';
import {AmapMarkerDirective} from 'ngx-amap';

export interface Block {
  hash: string;
  timestamp: string;
  index: number;
  data: string;
  previousHash: string;
}

@Component({
  selector: 'app-trace',
  templateUrl: './trace.component.html',
  styleUrls: ['./trace.component.scss']
})
export class TraceComponent implements OnInit, AfterViewInit {
  car: AmapMarkerDirective;
  passedPath: number[][];
  batchId: string;
  blockInfo: any = [];
  foodInfo: any = [];
  batchCode: string;
  foodName: string;
  manufacture: string;
  manufactureId: string;
  manuLocation: any;
  pd: string;
  ld: string;
  batchInput: string;
  barcodeInput: string;
  searchedBatch: string;
  checkStandards: string;
  checkDepartment: string;
  checkDate: string;
  transCode: string;
  transDepartment: string;
  transInfo: any = [];
  transLocation: any[];
  qsCode: string;
  qsStartTime: string;
  qsEndTime: string;

  @ViewChildren(AmapMarkerDirective) markers: QueryList<AmapMarkerDirective>;

  constructor(private route: ActivatedRoute,
              private router: Router,
              private http: HttpClient) {
    this.route.queryParams.subscribe(params => {
      this.batchId = params['batch'];
      if (this.batchId) {
        sessionStorage.setItem('batch', this.batchId);
      } else {
        this.batchId = sessionStorage.getItem('batch');
      }
      this.loadData();
    });
  }

  submit() {
    if (this.batchInput && this.barcodeInput) {
      const formData = new FormData();
      formData.append('Barcode', this.barcodeInput);
      formData.append('Batch', this.batchInput);
      this.http.post(SERVER_URL + '?s=App.Publicindex.Select1', formData).subscribe((data: ReturnData) => {
        if (data.data.code) {
          this.searchedBatch = data.data.code[0].batchId;
          this.router.navigate(['/public/trace'], {queryParams: {'batch': this.searchedBatch}});
        } else {
          alert('没有找到');
        }
      });
    }


  }

  async loadData() {
    const blockInfoReturnData = await this.http.post(BLOCK_URL + 'getFoodInfo', {data: {'batchId': this.batchId}}).toPromise();
    const foodInfoReturnData = await this.http.get<ReturnData>(SERVER_URL + '?s=App.Publicindex.Select3&Batchid=' + this.batchId).toPromise();
    if (blockInfoReturnData && foodInfoReturnData) {
      this.blockInfo = blockInfoReturnData;
      this.foodInfo = foodInfoReturnData.data.id[0];
      for (const f of this.blockInfo) {
        if (f.data.type === 1) {
          this.batchCode = f.data.batchCode;
          this.foodName = f.data.fName;
          this.manufacture = f.data.fmName;
          this.manufactureId = f.data.fmId;
          const manuInfoReturnData = await this.http
            .get<ReturnData>(SERVER_URL + '?s=App.Manufacturer.Selectaddress&id=' + this.manufactureId).toPromise();
          if (manuInfoReturnData.data.code[0].Lat && manuInfoReturnData.data.code[0].Lng) {
            this.manuLocation = [manuInfoReturnData.data.code[0].Lng, manuInfoReturnData.data.code[0].Lat];
            if (!this.transLocation) {
              this.transLocation = [];
            }
            this.transLocation.unshift(this.manuLocation);
          }
          this.pd = f.data.pd;
          this.ld = f.data.ld;
        } else if (f.data.type === 2) {
          this.checkStandards = f.data.pStandard;
          this.checkDepartment = f.data.department;
          this.checkDate = f.data.date;
        } else if (f.data.type === 3) {
          this.transCode = f.data.transId;
          this.transDepartment = f.data.company;
          this.transInfo.push({'time': f.data.time, 'destination': f.data.destination});
          const arr = [f.data.lng, f.data.lat];
          if (!this.transLocation) {
            this.transLocation = [];
          }
          this.transLocation.push(arr);
        }
      }
      this.http.post<Block>(BLOCK_URL + 'getQsCode', {data: {manuId: this.manufactureId}}).subscribe(data => {
        if (data[0]) {
          this.blockInfo.push(data[0]);
          this.qsCode = data[0].data.qsCode;
          this.qsStartTime = data[0].data.qsStartTime;
          this.qsEndTime = data[0].data.qsEndTime;
        }
      });
    }
  }

  ngOnInit() {
    console.log(this.transLocation);
  }

  ngAfterViewInit() {
    this.car = this.markers.last;
  }

  onMarkerReady(map: any) {
    map.setFitView();
  }

  startMove() {
    this.car.moveAlong(this.transLocation, 50000);
  }

  onMoving(event) {
    this.passedPath = event.passedPath;
  }
}
